package com.crl.ui.controls
{
	import com.crl.ui.controls.buttons.RadioButton;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.MouseEvent;
	
	/**
	 * ...
	 * @author crl
	 */
	public class RadioButtonGroup extends EventDispatcher
	{
		private var buttons:Array;
		
		private var currentSelect:RadioButton;
		public function RadioButtonGroup() 
		{
			buttons = new Array();
		}
		
		public function getButtons():Array{
			return buttons;
		}
		
		public function getSelect():RadioButton{
			return this.currentSelect;
		}
		
		/**
		 * Static method to add the newly created RadioButton to the list of buttons in the group.
		 * @param rb The RadioButton to add.
		 */
		public function addButton(rb:RadioButton):Boolean
		{
			if(buttons.indexOf(rb) !=-1)return false;
			
			rb.addEventListener(MouseEvent.CLICK, clickHanlder,false,0,true);
			buttons.push(rb);
			return true;
		}
		
		public function removeButton(rb:RadioButton):Boolean{
			var index:int=buttons.indexOf(rb) 
			if(index==-1)return false;
			
			rb.removeEventListener(MouseEvent.CLICK, clickHanlder);
			
			buttons.splice(index,1);
			return true;
		}
		
		private function clickHanlder(event:Event):void {
			var rb:BaseRadioButton= event.currentTarget as RadioButton;
			if(rb.selected){
				
				this.clear(rb);
			}
		}
		
		public function select(index:int=0):void{
			var len:int=buttons.length;
			index=Math.min(len,Math.max(0,index));
			
			var radio:BaseRadioButton=buttons[index] as RadioButton;
			radio.selected=true;
			this.clear(radio);
		}
		
		private function clear(rb:RadioButton):void
		{
			for(var i:uint = 0; i < buttons.length; i++)
			{
				if(buttons[i] != rb)
				{
					buttons[i].selected = false;
				}
			}
			currentSelect=rb;
			
			this.dispatchEvent(new Event(Event.SELECT));
		}
		
	}
	
}